import React from "react";
import type { DataAction, IProTableRef } from "@yaf/pro-ui";
import { getUserPageList, createUser, updateUserInfo, deleteUserInfo, getUserInfo } from "../../api";

export const getDataAction = (proTableRef: React.MutableRefObject<IProTableRef>, deptId: number): DataAction => ({
  fetchList: (params) => {
    const { page, pageSize, filter } = params;
    return new Promise((resolve, reject) => getUserPageList(Object.assign({ page, pageSize, deptId }, filter || {})).then((resp) => resolve(resp.data)).catch((e) => reject(e)))
  },
  getItem: (rowKey) => {
    const userId = rowKey as number;
    return new Promise((resolve, reject) => getUserInfo(userId).then((resp) => {
      const { user, checkedPosts,checkedRoleIds, checkedAdminRoleId} = resp.data;
      resolve({
        userId: user.id,
        nickName: user.userNickname,
        userName: user.userName,
        deptId: user.deptId,
        mobile: user.mobile,
        email: user.userEmail,
        status: user.userStatus,
        sex: user.sex.toString(),
        isAdmin: user.isAdmin,
        remark: user.remark,
        postIds: checkedPosts,
        roleIds: checkedRoleIds || [],
        adminRoleId: checkedAdminRoleId,
      })
    }).catch((e) => reject(e)));
  },
  createItem: (params) => {
    return new Promise((resolve, reject) => createUser(params).then((resp) => {
      proTableRef.current.doFetchList();
      resolve(resp.data)
    }).catch((e) => reject(e)))
  },
  updateItem: (rowKey, params) => {
    params.userId = rowKey;
    return new Promise((resolve, reject) => updateUserInfo(params).then((resp) => {
      proTableRef.current.doFetchList();
      resolve(resp.data)
    }).catch((e) => reject(e)))
  },
  deleteItems: (selectedRowKeys) => {
    return deleteUserInfo(selectedRowKeys.map((item) => parseInt(item)))
  },
})


